package com.ht.medicaltreatment.activity

import android.content.Intent
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ClickUtils
import com.blankj.utilcode.util.GsonUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.gym.baselib.base.BaseActivity
import com.ht.medicaltreatment.R
import com.ht.medicaltreatment.adapter.ChangePDAdapter
import com.ht.medicaltreatment.bean.ChangeInventoryListBean
import com.ht.medicaltreatment.bean.PDQueryBoxBean
import com.ht.medicaltreatment.view.ProjectDialog
import com.ht.medicaltreatment.view.TypeDialog
import com.ht.medicaltreatment.viewmodel.BuildOrderViewModel
import com.xgst.lib.utils.showToast
import kotlinx.android.synthetic.main.activity_build_order_layout.*

//修改盘点计划
class ChangeInventoryOrderActivity:BaseActivity(), View.OnClickListener, OnItemClickListener {
    override fun getLayoutId() = R.layout.activity_build_order_layout

    private var projectId = ""
    private var typeId = ""
    private var id = ""
    private var sampleBoxName = ""
    private var inventorySampleBoxIds = ""
    private val model by viewModels<BuildOrderViewModel>()
    private val adapter = ChangePDAdapter()
    //网络获取的
    private val netList = mutableListOf<ChangeInventoryListBean>()
    //本地获取的
    private val localList = mutableListOf<ChangeInventoryListBean>()

    override fun init() {
        setTitle("修改盘点计划")
        tvProjectName.setOnClickListener(this)
        tvSampleType.setOnClickListener(this)
        imgSampleType.setOnClickListener(this)
        btnStart.setOnClickListener(this)
        btnPositive.setOnClickListener(this)
        imgDelete.setOnClickListener(this)
        cbAll.setOnClickListener(this)
        clRoot.visibility = View.VISIBLE
        btnPositive.visibility = View.VISIBLE
        btnPositive.text = "修改"
        ClickUtils.expandClickArea(imgDelete,30)

        val planId = intent.getIntExtra("id",-1)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = adapter
        adapter.setOnItemClickListener(this)
        netList.clear()
        model.reuqestSampleBox("$planId"){
            etName.setText(it.inventoryTable.name)
            id = "${it.inventoryTable.id}"
            it.inventorySampleBoxList.forEach { bean ->
                netList += ChangeInventoryListBean(
                    deleteId = "${bean.id}",
                    changeId = "${bean.rfidSampleBox?.id}",
                    isChecked = false,
                    checkStatus = bean.checkStatus,
                    sampleCategory = bean.rfidSampleBox?.sampleCategory?:"",
                    name = bean.rfidSampleBox?.name?:"",
                    isLocal = false
                )
            }
            adapter.setNewInstance(netList)
            tvCheckCount.text = "${adapter.data.size}"
        }
    }

    override fun isViewStup() = true

    override fun onClick(v: View?) {
        when(v){

            //项目
            tvProjectName -> {
                ProjectDialog(this).show {id,name ->
                    tvProjectName.text = name
                    projectId = "$id"
                }
            }

            //样本类型
            tvSampleType -> {
                TypeDialog(this).show { id, name ->
                    tvSampleType.text = name
                    typeId = "$id"
                }
            }

            cbAll -> {
                adapter.data.forEach {
                    it.isChecked = cbAll.isChecked
                }
                adapter.notifyDataSetChanged()
            }

            //删除
            imgDelete -> {
                inventorySampleBoxIds = ""
                val deleteNetList = adapter.data.filter { it.isChecked && !it.isLocal }
                val deleteLocalList = adapter.data.filter { it.isChecked && it.isLocal }
                if(deleteNetList.size > 0){
                    showProgress()
                    deleteNetList.forEach {
                        if(inventorySampleBoxIds.isEmpty()){
                            inventorySampleBoxIds = "${it.deleteId}"
                        }else{
                            inventorySampleBoxIds = "$inventorySampleBoxIds,${it.deleteId}"
                        }
                    }
                    model.delete(inventorySampleBoxIds){
                        dismissProgress()
                        deleteNetList.forEach {
                            adapter.remove(it)
                        }
                        tvCheckCount.text = "${adapter.data.size}"
                    }
                }

                if(deleteLocalList.size > 0){
                    deleteLocalList.forEach {
                        adapter.remove(it)
                        tvCheckCount.text = "${adapter.data.size}"
                    }
                }

            }

            //查询
            btnStart -> {
                val intent = Intent(this,InventoryQueryActivity::class.java)
                intent.putExtra("projectId",projectId)
                intent.putExtra("sampleBoxName",sampleBoxName)
                intent.putExtra("sampleCategoryId",typeId)

                val list = arrayListOf<PDQueryBoxBean>()
                adapter.data.forEach {
                    list += PDQueryBoxBean(id = it.changeId.toInt())
                }
                intent.putExtra("json",GsonUtils.toJson(list))

                startActivityForResult(intent){
                    val list = GsonUtils.fromJson<MutableList<PDQueryBoxBean>>(
                        it?.getStringExtra("json"),genericType<MutableList<PDQueryBoxBean>>())
                    val newList = mutableListOf<ChangeInventoryListBean>()
                    list.forEach {
                        newList += ChangeInventoryListBean(
                            deleteId = "",
                            changeId = "${it.id}",
                            isChecked = false,
                            checkStatus = 0,
                            sampleCategory = it.sampleCategory,
                            name = it.name,
                            isLocal = true
                        )
                    }
                    adapter.addData(newList)
                    localList.addAll(newList)
                    tvCheckCount.text = "${adapter.data.size}"
                }
            }

            btnPositive -> {
                val name = etName.text.toString()
                if(name.isEmpty()){
                    showToast("请输入表单名称")
                    return
                }
                var boxIds = ""
                adapter.data.forEach {
                    if(it.checkStatus == 0){
                        if(boxIds.isEmpty()){
                            boxIds = it.changeId
                        }else{
                            boxIds = "$boxIds,${it.changeId}"
                        }
                    }
                }
                showProgress()
                model.revise(id,name,boxIds){
                    dismissProgress()
                    setResult(RESULT_OK)
                    finish()
                }
            }
        }
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = adapter.getItem(position) as ChangeInventoryListBean
        if(item.checkStatus == 1){
            showToast("已核验，无法修改")
            return
        }
        item.isChecked = !item.isChecked
        adapter.notifyItemChanged(position)
        val list = adapter.data as MutableList<ChangeInventoryListBean>
        val bean = list.find { !it.isChecked }
        if(bean == null){
            cbAll.isChecked = true
        }else{
            if(cbAll.isChecked){
                cbAll.isChecked = false
            }
        }
    }
}

